package com.example.teacher.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.domain.pojo.Rethink;
import com.example.common.utils.CacheClient;
import com.example.teacher.Service.RethinkService;
import com.example.teacher.mapper.RethinkMapper;
import jakarta.persistence.EntityNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

@Service
@Slf4j
public class RethinkServiceImpl extends ServiceImpl<RethinkMapper, Rethink> implements RethinkService {

    @Autowired
    private CacheClient cacheClient;
    @Autowired
    private RethinkMapper rethinkMapper;


    @Override
    public void updateRethink(Rethink rethink) {
        // 参数校验：确保主键存在
        if (rethink.getId() == null) {
            log.warn("更新反思时必须提供id");
            throw new IllegalArgumentException("更新反思时必须提供id");
        }

        // 构建UpdateWrapper
        UpdateWrapper<Rethink> updateWrapper = new UpdateWrapper<>();

        // 设置更新条件（主键）
        updateWrapper.lambda().eq(Rethink::getId, rethink.getId());

        // 动态设置需要更新的字段（只更新非null值）
        LambdaUpdateWrapper<Rethink> lambdaUpdate = updateWrapper.lambda();

        // 根据非null值设置更新字段
        if (rethink.getContent() != null) {
            lambdaUpdate.set(Rethink::getContent, rethink.getContent());
        }
        if (rethink.getTeacherId() != null) {
            lambdaUpdate.set(Rethink::getTeacherId, rethink.getTeacherId());
        }
        if (rethink.getCourseId() != null) {
            lambdaUpdate.set(Rethink::getCourseId, rethink.getCourseId());
        }
        if (rethink.getClassId() != null) {
            lambdaUpdate.set(Rethink::getClassId, rethink.getClassId());
        }

        // 自动更新时间戳
        lambdaUpdate.set(Rethink::getUpdate_at, new Timestamp(System.currentTimeMillis()));

        // 执行更新操作
        int rows = rethinkMapper.update(null, updateWrapper);

        // 检查更新结果
        if (rows == 0) {
            log.warn("更新反思失败，未找到记录，id={}", rethink.getId());
            throw new EntityNotFoundException("未找到对应反思记录，id=" + rethink.getId());
        }
    }
}
